import router from "@/router";
import { getMenuList } from "@/api/login/login";
import Layout from "@/layout/base-layout/index.vue";
import EmptyLayout from "@/layout/empty-layout/index.vue";
import View from "@/layout/base-layout/view.vue";

export default {
  namespaced: true,
  state: {
    // 后台返回的菜单接口
    menuApi: [],
    // 子路由集合 str
    subRoutes: {},
    // 所有需要添加的路由
    allRouters: {},
    // 菜单数据
    menuList: [],
    // 按钮权限
    permissions: [],
    // 面包屑数据
    breadcrumbList: {},
    // 默认展示页面
    homePath: "",
  },
  actions: {
    GenerateRoutes({ state }) {
      return new Promise((resove) => {
        getMenuList().then((res) => {
          state.menuApi = res.list || [];
          // 生成子路由str
          state.subRoutes = menuApi2ModulesStr(state.menuApi);
          // // 生成路由
          state.allRouters = menuApi2Router(state.menuApi);
          state.allRouters.forEach((item) => {
            router.addRoute(item);
            router.options.routes.push(item);
          });
          // 处理菜单
          state.menuList = meunApi2List(state.menuApi);
          // 处理面包屑
          state.breadcrumbList = meunApi2Breadcrumb(router.options.routes);
          // 用户按钮权限
          state.permissions = res.permissions;
          // 获取默认页面路由
          state.homePath = getHomePath(state.menuApi);
          resove();
        });
      });
    },
    logout({ state }) {
      state.menuApi = [];
      state.menuList = [];
      state.permissions = [];
      state.breadcrumbList = {};
      state.homePath = "";
      router.options.DynamicMenuRoutes = false;
    },
  },
};

// 接口生成子路由str
function menuApi2ModulesStr(arr) {
  const data = JSON.parse(JSON.stringify(arr));
  const modulesArr = data.filter((item) => {
    return item.meta && item.meta.modules;
  });
  const subRoutes = {};
  const hasModulesChildren = (item) => {
    if (!item.children) {
      if (!subRoutes[item.meta.modules]) {
        subRoutes[item.meta.modules] = [];
      }
      subRoutes[item.meta.modules].push({
        ...item,
        path: item.meta.modules + "/" + item.path,
      });
    }
    if (item.children && item.children.length > 0) {
      item.children.map((v) => {
        hasModulesChildren(v);
      });
    }
  };
  modulesArr.map((v) => hasModulesChildren(v));
  return subRoutes;
}

// 接口转路由
function menuApi2Router(arr) {
  // 处理属于main包的路由
  const data = JSON.parse(JSON.stringify(arr));
  const mainArr = data.filter((item) => {
    return !item.meta || !item.meta.modules;
  });
  const mainData = [];
  const hasMainChildren = (item, parentNode) => {
    const obj = {};
    if (item.path) {
      obj.path = item.path;
    }
    if (item.meta) {
      obj.meta = item.meta;
    }
    if (item.name) {
      obj.name = item.name;
    }
    if (item.redirect) {
      obj.redirect = item.redirect;
    }
    if (item.component) {
      obj.component = loadView(item.component);
    }
    if (item.children && item.children.length > 0) {
      obj.children = [];
    }
    parentNode.push(obj);
    if (item.children && item.children.length > 0) {
      item.children.map((v) => {
        hasMainChildren(v, parentNode[parentNode.length - 1].children);
      });
    }
  };
  mainArr.map((v) => hasMainChildren(v, mainData));

  // 处理所有子包的路由
  const modulesArr = data.filter((item) => {
    return item.meta && item.meta.modules;
  });
  const modulesData = [];
  const hasModulesChildren = (item, parentNode) => {
    const obj = {};
    if (item.path) {
      obj.path = item.path;
      if (item.component === "Layout") {
        obj.path = "/modules/" + item.meta.modules + obj.path;
      }
    }
    if (item.meta) {
      obj.meta = item.meta;
    }
    if (item.name) {
      obj.name = item.name;
    }
    if (item.redirect) {
      obj.redirect = item.redirect;
      if (item.component === "Layout") {
        obj.redirect = "/modules/" + item.meta.modules + obj.redirect;
      }
    }
    if (item.component) {
      obj.component = loadView(item.component, true);
    }
    if (item.children && item.children.length > 0) {
      obj.children = [];
    }
    parentNode.push(obj);
    if (item.children && item.children.length > 0) {
      item.children.map((v) => {
        hasModulesChildren(v, parentNode[parentNode.length - 1].children);
      });
    }
  };
  modulesArr.map((v) => hasModulesChildren(v, modulesData));
  return [
    ...mainData,
    ...modulesData,
    {
      path: "*",
      redirect: "/404",
    },
  ];
}

// 接口转菜单
function meunApi2List(arr) {
  let newData = [];
  let data = JSON.parse(JSON.stringify(arr));
  const hasChildren = (item, parentPath, parentNode) => {
    const obj = {};
    if (item.path) {
      if (parentPath.indexOf("/") !== 0 && item.path.indexOf("/") !== 0) {
        parentPath = "/" + parentPath;
      }
      if (
        parentPath.lastIndexOf("/") !== parentPath.length - 1 &&
        item.path.indexOf("/") !== 0
      ) {
        item.path = "/" + item.path;
      }
      obj.path = parentPath + item.path;
      if (item.meta && item.meta.modules && !obj.path.startsWith("/modules")) {
        obj.path = "/modules/" + item.meta.modules + obj.path;
      }
    }
    if (item.meta) {
      obj.meta = item.meta;
    }
    if (item.children && item.children.length > 0) {
      obj.children = [];
    }
    obj.hidden = !!item.hidden;
    if (!obj.hidden) {
      parentNode.push(obj);
    }
    if (item.children && item.children.length > 0) {
      item.children.map((v) => {
        hasChildren(
          v,
          parentNode[parentNode.length - 1].path,
          parentNode[parentNode.length - 1].children
        );
      });
    }
  };
  data.map((v) => hasChildren(v, "", newData));
  const filterChildren = (arr) => {
    for (let i = arr.length - 1; i >= 0; i--) {
      const item = arr[i];
      // 这里就不继续递归了 一级菜单只有一个二级菜单 就升级为一级菜单
      // if (item.children && item.children.length > 0) {
      //   filterChildren(item.children);
      // }
      if (item.children?.length === 1) {
        const child = item.children[0];
        arr[i] = child;
      }
    }
  };
  filterChildren(newData);
  return newData;
}

// 接口转面包屑
function meunApi2Breadcrumb(arr) {
  const breadcrumbData = {};
  let newData = [];
  let data = JSON.parse(JSON.stringify(arr));
  const hasChildren = (item, parentPath, parentNode) => {
    const obj = {};
    if (item.path) {
      if (parentPath.indexOf("/") !== 0 && item.path.indexOf("/") !== 0) {
        parentPath = "/" + parentPath;
      }
      if (
        parentPath.lastIndexOf("/") !== parentPath.length - 1 &&
        item.path.indexOf("/") !== 0
      ) {
        item.path = "/" + item.path;
      }
      obj.path = parentPath + item.path;
    }
    if (item.meta) {
      obj.meta = item.meta;
    }
    if (item.children && item.children.length > 0) {
      obj.children = [];
    }
    obj.hidden = !!item.hidden;
    parentNode.push(obj);
    if (item.children && item.children.length > 0) {
      item.children.map((v) => {
        hasChildren(
          v,
          parentNode[parentNode.length - 1].path,
          parentNode[parentNode.length - 1].children
        );
      });
    }
  };
  data.map((v) => hasChildren(v, "", newData));
  const filterChildren = (arr) => {
    for (let i = arr.length - 1; i >= 0; i--) {
      const item = arr[i];
      if (item.children?.length === 1) {
        const child = item.children[0];
        arr[i] = child;
      }
    }
  };
  filterChildren(newData);
  const converDeep = [];
  const convertData = (arr) => {
    arr.map((item) => {
      // if (item.path === "/modules") {
      //   debugger;
      // }
      converDeep.push(JSON.parse(JSON.stringify(item)));
      if (item.children && item.children.length > 0) {
        convertData(item.children);
      }
      breadcrumbData[item.path] = JSON.parse(JSON.stringify(converDeep));
      converDeep.pop();
    });
  };
  convertData(newData);
  return breadcrumbData;
}

// 获取默认页面路由
function getHomePath(arr) {
  let path = "";
  let obj = arr.filter((item) => {
    return item.path === "/";
  });
  if (obj.length === 1) {
    obj = obj[0];
    obj = arr.filter((item) => {
      return item.path === obj.redirect;
    });
    if (obj.length === 1) {
      obj = obj[0];
    }
  }
  path = obj.redirect;
  return path;
}

// 加载组件
export const loadView = (view, modules) => {
  if (view.indexOf("/") === 0) {
    view = view.slice(1);
  }
  if (view === "Layout") {
    return Layout;
  } else if (view === "EmptyLayout") {
    return EmptyLayout;
  }
  if (modules) {
    return View;
  }
  return () => Promise.resolve(require(`@/views/${view}.vue`).default);
};
